<template>
  <div class="ai-assistant">
    <a-float-button-group trigger="click" tooltip="帮助" :style="{ right: '2vw', bottom: '12vh' }">
      <template #icon>
        <QuestionOutlined />
      </template>
      <a-float-button @click="openChat" :badge="{ count: 1 }" tooltip="AI助手">
        <template #icon>
          <RobotOutlined class="robot-icon" />
        </template>
      </a-float-button>
    </a-float-button-group>

    <a-modal
      v-model:visible="isChatOpen"
      title="AI 助手"
      width="80vw"
      :footer="null"
      @cancel="closeChat"
      class="chat-modal"
    >
      <div class="chat-container">
        <div class="chat-box" ref="chatBox">
          <div
            v-for="(message, index) in chatMessages"
            :key="index"
            :class="['message-container', message.role]"
          >
            <div v-if="message.role === 'ai'" class="avatar ai-avatar">
              <a-spin :spinning="loading">
                <RobotOutlined />
              </a-spin>
            </div>

            <div :class="['message-bubble', message.role]">
              <div class="message-content">{{ message.text }}</div>
            </div>

            <div v-if="message.role === 'user'" class="avatar user-avatar">
              <UserOutlined />
            </div>
          </div>
        </div>

        <div class="scroll-indicator" @click="scrollToBottom">
          <DownCircleTwoTone class="scroll-icon" />
        </div>

        <div class="input-container">
          <a-row gutter="10">
            <a-col :span="20">
              <a-input
                v-model:value="userInput"
                placeholder="请输入您的问题"
                @pressEnter="sendMessage"
                size="large"
                block=""
              >
              </a-input>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="3">
              <a-button
                type="primary"
                :disabled="loading"
                :icon="h(SendOutlined)"
                block
                @click="sendMessage"
              />
            </a-col>
          </a-row>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { h, nextTick, onMounted, onUnmounted, ref } from 'vue'
import {
  DownCircleTwoTone,
  QuestionOutlined,
  RobotOutlined,
  SendOutlined,
  UserOutlined,
} from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user.ts'
import { Modal } from 'ant-design-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

interface Message {
  role: 'user' | 'ai'
  text: string
}

const isChatOpen = ref(false)
const chatMessages = ref<Message[]>([])
const userInput = ref('')
const isScrolling = ref(false)
const chatBox = ref<HTMLDivElement | null>(null)
const showScrollToBottomButton = ref(false)
let eventSource: EventSource | null = null
let scrollTimer: ReturnType<typeof setTimeout>

const loading = ref(false)
// 滚动处理
const handleScroll = () => {
  isScrolling.value = true
  clearTimeout(scrollTimer)
  scrollTimer = setTimeout(() => (isScrolling.value = false), 200)

  if (chatBox.value) {
    const { scrollTop, scrollHeight, clientHeight } = chatBox.value
    showScrollToBottomButton.value = scrollHeight - scrollTop - clientHeight > 100
  }
}

const scrollToBottom = () => {
  if (chatBox.value) {
    chatBox.value.scrollTo({
      top: chatBox.value.scrollHeight,
      behavior: 'smooth',
    })
    showScrollToBottomButton.value = false
  }
}

const openChat = () => {
  isChatOpen.value = true
}

const closeChat = () => {
  isChatOpen.value = false
  chatMessages.value = []
  userInput.value = ''
  eventSource?.close()
  loading.value = false
}

// 消息处理
const sendMessage = async () => {
  const input = userInput.value.trim()
  if (!input) return

  const userStore = useUserStore()
  if (!userStore.isLogin) {
    Modal.confirm({
      title: '提示',
      content: '请先登录',
      okText: '去登录',
      onOk: () => router.push('/user/login'),
    })
    return
  }

  loading.value = true

  // 添加用户消息
  const userMessage: Message = { role: 'user', text: userInput.value }
  chatMessages.value.push(userMessage)
  userInput.value = ''

  // 创建AI消息占位
  chatMessages.value.push({ role: 'ai', text: '' })

  await nextTick(scrollToBottom)

  // 创建 SSE 连接
  if (eventSource) {
    eventSource.close() // 如果已有连接，先关闭
  }

  const baseUrl = import.meta.env.VITE_APP_API_URL || ''
  const sseUrl = `${baseUrl}/api/ai/app/assistant?prompt=${encodeURIComponent(userMessage.text)}`
  console.log('Connecting to SSE:', sseUrl)

  eventSource = new EventSource(sseUrl)

  // 接收消息
  eventSource.onmessage = (event) => {
    console.log('Received SSE message:', event.data)
    const aiResponseText = event.data
    // 自动滚动到底部
    chatMessages.value[chatMessages.value.length - 1].text += aiResponseText

    if (aiResponseText == '') {
      loading.value = false
    }
  }

  // 处理错误
  eventSource.onerror = (error) => {
    console.error('SSE connection error:', error)
    if (eventSource) {
      eventSource.close()
      eventSource = null
    }

    // 显示默认错误消息
    const errorMessage: Message = {
      role: 'ai',
      text: '抱歉，AI助手暂时无法回答您的问题。',
    }
    if (chatMessages.value[chatMessages.value.length - 1].role === 'user') {
      chatMessages.value.push(errorMessage)
    }
  }
}

// 生命周期
onMounted(() => {
  if (chatBox.value) {
    chatBox.value.addEventListener('scroll', handleScroll)
  }
})

onUnmounted(() => {
  if (chatBox.value) {
    chatBox.value.removeEventListener('scroll', handleScroll)
  }
  if (eventSource) {
    eventSource.close()
  }
})
</script>

<style scoped>
.ai-assistant {
  position: fixed;
  bottom: 40px;
  right: 40px;
  z-index: 1000;
}

.trigger-button {
  width: 60px;
  height: 60px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.robot-icon {
  font-size: 1em;
  transition: transform 0.3s;
}

.trigger-button:hover .robot-icon {
  transform: scale(1.1);
}

.chat-modal :deep(.ant-modal-body) {
  padding: 0;
}

.chat-container {
  position: relative;
  height: 70vh;
  display: flex;
  flex-direction: column;
}

.chat-box {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
}

.message-container {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.message-container.ai {
  flex-direction: row;
}

.message-container.user {
  flex-direction: row-reverse;
}

.avatar {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.ai-avatar {
  color: #1890ff;
}

.user-avatar {
  color: #52c41a;
}

.message-bubble {
  max-width: 75%;
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.6;
  position: relative;
  word-break: break-word;
}

.message-bubble.ai {
  background: #fff;
  color: #333;
  border-radius: 0 12px 12px 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.message-bubble.user {
  background: #1890ff;
  color: #fff;
  border-radius: 12px 0 12px 12px;
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.3);
}

.scroll-indicator {
  position: absolute;
  bottom: 80px;
  right: 30px;
  cursor: pointer;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 8px;
}

.scroll-icon {
  font-size: 28px;
  display: block;
}

.input-container {
  padding: 20px;
  border-top: 1px solid #eee;
  background: #fff;
}

.message-input :deep(.ant-input) {
  border-radius: 24px;
  padding: 12px 20px;
}

.send-icon {
  font-size: 20px;
  cursor: pointer;
  transition: color 0.3s;
}

@media (max-width: 768px) {
  .ai-assistant {
    bottom: 20px;
    right: 20px;
  }

  .trigger-button {
    width: 50px;
    height: 50px;
  }

  .robot-icon {
    font-size: 24px;
  }

  .message-bubble {
    max-width: 85%;
    padding: 10px 14px;
  }

  .avatar {
    width: 32px;
    height: 32px;
  }
}
</style>
